package MotionDetection;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.util.Log;

public class WheelMotionDetector implements MotionDetector {
	private int leftLastRead;
	private int rightLastRead;
	private boolean inMovement;
	boolean turnLeft;

	public WheelMotionDetector() {

	}

	public WheelMotionDetector(boolean turnLeft) {
		this.turnLeft = turnLeft;
	}

	@Override
	public boolean detectMotion(SensorEvent e) {
		if (e.sensor.getType() == Sensor.TYPE_ORIENTATION) {
			int pitch = (int) e.values[1];
			int roll = (int) e.values[2];
			int lambda = pitch < 0 ? roll - pitch : roll + pitch; //lambda = |pitch| + roll
			int direction = turnLeft ? 1 : -1;
			int checkLastRead = 0;
			
			if (pitch > 0 ? pitch < 7 : pitch > -7 )
				inMovement = false;
			
			if (turnLeft)
				checkLastRead = pitch - leftLastRead > 0 ? pitch - leftLastRead : leftLastRead - pitch; //|pitch - lastRead|
			else
				checkLastRead = pitch - rightLastRead > 0 ? pitch - rightLastRead : rightLastRead - pitch; //|pitch - lastRead|
			
			if (checkLastRead < 15)//Don't do continuous tests
				return false;
			
			if (turnLeft)
				leftLastRead = pitch;//update the last read
			else 
				rightLastRead = pitch;//update the last read
			
			if (roll < 1)//Don't decode when phone is "On the table"...
				return false;
			
			if (roll > 77 || pitch * direction > 100)
				return false;//Don't decode when phone is "leaning towards the user"
						
			if (lambda > 50)
				return returnHelper(direction * pitch > lambda - 30, pitch, roll, lambda);
			
			if (lambda > 20)
				return returnHelper(direction * pitch > 15, pitch, roll, lambda);
			
			return returnHelper(direction * pitch > 7, pitch, roll, lambda);
		}
		return false;
	}
	
	private boolean returnHelper(boolean result, int pitch,int roll,int lambda)
	{
		if (result && !inMovement)
		{
			if ((turnLeft && pitch < 0) || (!turnLeft && pitch > 0))
				return false;
			
			Log.d("Sensor", turnLeft + " pitch: " + pitch + " roll: " + roll + " |p| + r = " + lambda);
			inMovement = true;
			return true;
		}
		return false;
	}
}
